<template>
  <!-- 产品与器具型号表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="500px"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100">
      <el-row>
        <el-col :span="24">
          <el-form-item label="产品" prop="productId">
            <el-select
              v-model="formData.productId"
              placeholder="请选择产品"
              clearable
              @change="productCenter"
              v-if="!props.isReadonly"
              style="width: 350px"
            >
              <el-option
                v-for="item in productist"
                :key="`${item.id}`"
                :label="`${item.productCode}-${item.productName}`"
                :value="`${item.id}`"
              />
            </el-select>

            <span v-else>{{ formData.productName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="器具类型" prop="assetTypeId">
            <el-tree-select
              v-if="!props.isReadonly"
              placeholder="请选择器具类型"
              v-model="formData.assetTypeId"
              :data="catalogList"
              node-key="id"
              :props="{
                label: 'assetTypeName',
                value: 'id',
                children: 'nodes',
              }"
              :render-after-expand="false"
              :check-strictly="true"
              style="width: 350px"
              clearable
              @node-click="selectAssetType"
            />
            <span v-else>{{ formData.assetTypeName }}</span>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24">
          <el-form-item label="制造商" prop="makerId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.makerId"
              placeholder="请选择制造商"
              style="width: 300px"
              clearable
              @change="(e) => handleMakerChange(e, 'row')"
            >
              <el-option
                v-for="item in makerList"
                :key="`${item.id}`"
                :label="`${item.makerCode}-${item.makerName}`"
                :value="`${item.id}`"
              />
            </el-select>

            <span v-else
              >{{ formData.makerCode }}{{ formData.makerName ? "-" : ""
              }}{{ formData.makerName }}</span
            >
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="24">
          <el-form-item label="品牌型号" prop="assetModelId">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.assetModelId"
              placeholder="请选择品牌型号"
              style="width: 300px"
              clearable
              @change="handelBrandModelNo"
            >
              <el-option
                v-for="item in brandModelList"
                :key="`${item.id}`"
                :label="`${item.brandName}-${item.modelNo}`"
                :value="`${item.id}`"
              />
            </el-select>

            <span v-else
              >{{ formData.assetBrandName
              }}{{ formData.assetBrandName ? "-" : ""
              }}{{ formData.assetModelNo }}</span
            >
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="24">
          <el-form-item label="器具型号" prop="assetModelId">
            <el-select
              v-model="formData.assetModelId"
              placeholder="请选择器具型号"
              clearable
              @change="modeCenter"
              v-if="!props.isReadonly"
              style="width: 300px"
            >
              <el-option
                v-for="item in modelist"
                :key="`${item.id}`"
                :label="`${item.modelNo}`"
                :value="`${item.id}`"
              />
            </el-select>

            <span v-else>{{ formData.assetModelNo }}</span>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="启用状态" prop="enabled">
            <el-radio-group v-model="formData.enabled" v-if="!props.isReadonly">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
            <span v-else>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "EAMEAMPRODUCTASSETMODELADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
      getCAtalogList();
    }, 50);
  }
);

const rules = reactive({
  version: [],
  plantId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  plantCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  productId: [{ required: true, message: "请选择产品", trigger: "change" }],
  productCode: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  productName: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  assetKind: [],
  assetTypeId: [
    { required: true, message: "请选择器具类型", trigger: "change" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  assetModelId: [
    { required: true, message: "请选择器具品牌型号", trigger: "change" },
  ],
  // assetModelNo: [
  //   {  required: true, message: "请选择器具型号", trigger: "change" },
  // ],
  makerId: [{ required: true, message: "请选择制造商", trigger: "change" }],
  assetBrandId: [{ required: true, message: "请选择品牌", trigger: "change" }],

  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  enabled: [],
  deleted: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  plantId: "",
  plantCode: "",
  productId: "",
  productCode: "",
  productName: "",
  assetKind: "",
  assetTypeId: "",
  assetTypeName: "",
  makerId: "",
  makerName: "",
  makerCode: "",
  assetBrandId: "",
  assetBrandName: "",
  assetModelId: "",
  assetModelNo: "",
  organizationId: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        plantId,
        plantCode,
        productId,
        productCode,
        productName,
        assetKind,
        assetTypeId,
        assetTypeName,
        assetModelId,
        assetModelNo,
        organizationId,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        makerId,
        makerName,
        makerCode,
        assetBrandId,
        assetBrandName,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        plantId,
        plantCode,
        productId,
        productCode,
        productName,
        assetKind,
        assetTypeId,
        assetTypeName,
        assetModelId,
        assetModelNo,
        organizationId,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        makerId,
        makerName,
        makerCode,
        assetBrandId,
        assetBrandName,
      });
      //  编辑时获取品牌型号数据
      handleMakerChange(formData.makerId);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.productId = "";
  formData.productCode = "";
  formData.productName = "";
  formData.assetKind = "";
  formData.assetTypeId = "";
  formData.assetTypeName = "";
  formData.assetModelId = "";
  formData.assetModelNo = "";
  formData.organizationId = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.makerId = "";
  formData.makerName = "";
  formData.makerCode = "";
  formData.assetBrandId = "";
  formData.assetBrandName = "";
}

const loading = ref(false);

/** 产品与器具型号保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      makerList.value.forEach((item) => {
        if (item.id == formData.makerId) {
          formData.makerName = item.makerName;
          formData.makerCode = item.makerCode;
        }
      });
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/mtproductassetmodel/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

//产品列表
const productist = ref([]);
const getProductist = async () => {
  const { data } = await request({
    url: "mdm/mdmproductinfo/getList",
    method: "post",
    data: {},
  });
  productist.value = data;
};

//型号列表
const modelist = ref([]);
const getModelist = async () => {
  const { data } = await request({
    url: "eam/mtAssetmodel/getList",
    method: "post",
    data: {},
  });
  modelist.value = data;
};

const productCenter = (id: any) => {
  formData.productId = id;
  productist.value.forEach((item) => {
    if (item.id === id) {
      formData.productCode = item.productCode;
      formData.productName = item.productName;
    }
  });
};

const modeCenter = (id: any) => {
  formData.assetModelId = id;
  modelist.value.forEach((item) => {
    if (item.id === id) {
      formData.assetModelNo = item.modelNo;
      formData.assetTypeId = item.assetTypeId;
    }
  });
};

// 获取制造商列表
const makerList: any = ref([]);
const getMakerList = async () => {
  request({
    url: `/eam/eammaker/getList`,
    method: "post",
    data: {},
  })
    .then((res) => {
      makerList.value = res.data;
    })
    .catch((res) => {
      console.log(res);
    });
};

// 点击制造商 返回品牌和型号
const brandModelList = ref([]);
const handleMakerChange = async (e, item) => {
  if (item == "row") {
    formData.assetBrandId = "";
    formData.assetBrandName = "";
    formData.assetModelId = "";
    formData.assetModelNo = "";
  }
  if (e) {
    brandModelList.value = [];
    // formData.assetModelId = "";
    const { data } = await request({
      url: "/eam/mtAssetmodel/getList",
      method: "POST",
      data: {
        makerId: e,
      },
    });

    brandModelList.value = data;
  } else {
    formData.assetModelId = "";
    formData.makerId = "";
    formData.makerName = "";
    brandModelList.value = [];
  }
};

// 点击品牌 赋值
const handelBrandModelNo = (e) => {
  if (e) {
    brandModelList.value.forEach((item) => {
      if (item.id == e) {
        formData.assetBrandId = item.brandId;
        formData.assetBrandName = item.brandName;
        formData.assetModelId = item.id;
        formData.assetModelNo = item.modelNo;
      }
    });
  } else {
    formData.assetBrandId = "";
    formData.assetBrandName = "";
    formData.assetModelId = "";
    formData.assetModelNo = "";
  }
};

// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/eamCommon/getAvailableTree",
    method: "POST",
    data: { assetKind: 2 },
  }).then((res) => {
    // console.log("formData.assetKind", res.data);
    catalogList.value = res.data;
  });
};

function selectAssetType(e: any) {
  console.log("e", e);
  formData.assetTypeId = e?.id || "";
  formData.assetTypeName = e?.assetTypeName || "";
}

onMounted(() => {
  getModelist();
  getProductist();
  getMakerList();
});
</script>
<style lang="scss" scoped></style>
